<?php 
/**
* Used internally by the engine to manage parameters (common behaviour between POST and GET)
*
* This class defines some default behaviours for parameters, either GET or POST.
* The $_GET or $_POST array is read, parsed, filtered for invalid values (like ../.. recursions)
* and imported into internal arrays. The global array is then emptied or deleted ($_POST cannot be
* deleted).
* Also, parameters can be read using the <i>GetParam</i> method in an efficient and secure way.
* The parameters can be dumped for debug purposes. 
*@package Core
*@subpackage Internals
*@author Willy Gardiol <willy@gardiol.org>
*@version 1.0
*/
class CoreParameters
{
	protected $vars = array();
	/**
	* Dump array for debug purposes
	*
	*/
	public function Dump()
	{
		return $this->vars;
	}
	/**
	* Read and parse the parameters 
	*
	* (@param string $type shall be either "post" or "get")
	* Read the global array, copy it into the internal array, unset/empty the global one
	* and then filter the stored copy for invalid/dangerous/unsave values.
	* Right now, only recursive (../../../../ etc) parameters are dropped as intrinsecally 
	* a security breach attempt
	*/
	public function __construct( $type )
	{
		switch ( $type )
		{
		case "get":
			$this->vars = $_GET;
			unset( $_GET );
			break;
		case "post":
			$this->vars = $_POST;
			$_POST = array();
			break;
		default:
			throw new Exception("Invalid type '$type' in Parameters class!");
		}

		foreach ( $this->vars as $k => $v )
			if ( strpos( $v, "../.." ) !== false )
				unset( $this->vars[$k] );
	}
	/**
	* return a GET or POST parameter (use default if none) with type-checking
	*
	* @param string $name Name of the parameter to return
	* @param mixed $default Default value to return if $name is not set
	* {@param string $type Either "bool" (boolean), "serialized" or anything else (will be considered string in this case)}
	* @return mixed Depends on $type...
	*/
	public function GetParam( $name, $default, $type )
	{
		if ( isset( $this->vars[$name] ) && ($this->vars[$name] != "var_is_uninited__")  )
		{	// First step: clean the value from bat characters and/or encoed inputs
			$x = strip_tags(stripslashes(trim(urldecode($this->vars[$name]))));

			// Second step: apply the requested type!
			switch ( $type )
			{
			case "boolean":
			case "bool":
			case "b":
				// Ensure $x is a valid boolean and convert strings or numbers to boolean
				if ( !is_bool( $x ) )
					$x = ( !(is_numeric( $x ) && ( $x == 0 )) && !( is_string( $x ) && ($x == "false") ));
				break;

			case "serialized":
				try
				{
					$x = CoreUtils::JsUnserialize( $x );
				}
				catch (Exception $x)
				{
					echo "Unserialize error: '$x'";
					$x = $default;
				}
				break;

			case "sequence":
				$x = explode(",", $x );
				if ( end($x) == "" )
					array_pop($x);
				break;

			}
			return $x;
		}
		return $default;
	}
}
?>